package auth

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"time"

	"github.com/golang-jwt/jwt/v5"
	"github.com/google/uuid"
)

// JWTManager JWT管理器
type JWTManager struct {
	secretKey []byte
}

// NewJWTManager 创建新的JWT管理器
func NewJWTManager(secretKey []byte) (*JWTManager, error) {
	if len(secretKey) == 0 {
		return nil, fmt.Errorf("JWT secret key cannot be empty")
	}

	return &JWTManager{
		secretKey: secretKey,
	}, nil
}

// GenerateRandomSecret 生成随机的JWT密钥
func GenerateRandomSecret() (string, error) {
	bytes := make([]byte, 32) // 256 bits
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return hex.EncodeToString(bytes), nil
}

// Claims 自定义JWT Claims
type Claims struct {
	ID   uuid.UUID `json:"id"`
	Name string    `json:"name"`
	jwt.RegisteredClaims
}

// GenerateToken 生成JWT Token
func (j *JWTManager) GenerateToken(id uuid.UUID, name string) (string, error) {
	claims := &Claims{
		ID:   id,
		Name: name,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), // 24小时过期
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "llm-gateway",
			Subject:   fmt.Sprintf("account_%d", id),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.secretKey)
}

// ValidateToken 验证JWT Token
func (j *JWTManager) ValidateToken(tokenString string) (*Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return j.secretKey, nil
	})

	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*Claims); ok && token.Valid {
		return claims, nil
	}

	return nil, fmt.Errorf("invalid token")
}
